package com.hand.wfive.activity.sign

import android.app.Dialog
import android.content.Intent
import android.widget.ImageView
import androidx.core.view.isInvisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.flyco.tablayout.listener.OnTabSelectListener
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.adapter.StampColorAdapter
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.entity.TabEntity
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.ImageUtils
import com.hand.wfive.util.bottomShow
import com.hand.wfive.util.click.NoFastClickUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import com.hand.wfive.util.seekBarChange
import com.hand.wfive.view.InputDialog
import kotlinx.android.synthetic.main.activity_make_stamp.*
import org.jetbrains.anko.find
import org.jetbrains.anko.toast
import kotlin.concurrent.thread

class MakeStampActivity : BaseActivity() {

    private lateinit var mColorDialog: Dialog

    override fun getContentViewId() = R.layout.activity_make_stamp

    override fun init() {
        topBar.setTitle("制作签章")
        topBar.addLeftBackImageButton().singleClick { finish() }
        topBar.addRightTextButton("保存", R.id.top_bar_right_text)
            .singleClick { onSave() }

        ctl_stamp_op.setTabData(
            arrayListOf(
                TabEntity("通用"), TabEntity("主标题"),
                TabEntity("副标题"), TabEntity("小标题")
            )
        )
        ctl_stamp_op.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabReselect(position: Int) = Unit
            override fun onTabSelect(position: Int) {
                if (position == 0) {
                    cl_whole.isInvisible = false
                    cl_title.isInvisible = true
                } else {
                    cl_whole.isInvisible = true
                    cl_title.isInvisible = false
                    when (position) {
                        1 -> loadTitleTop()
                        2 -> loadTitleBottom()
                        3 -> loadTitleCentre()
                    }
                }
            }
        })
        initWhole()
        initTitle()
    }

    private fun initWhole() {
        // 颜色
        iv_color.singleClick { showColorDialog() }
        // 边框粗细
        sb_frame_width.seekBarChange { _, i, _ -> stamp_view.setBigOvalWidth(i) }
        // 透明度
        sb_alpha.seekBarChange { _, i, _ -> stamp_view.setStampAlpha(i) }
        // 图案显示
        switch_show_star.setOnCheckedChangeListener { _, isChecked ->
            stamp_view.setShowStar(isChecked)
        }
    }

    private fun showColorDialog() {
        if (this::mColorDialog.isInitialized) {
            if (!mColorDialog.isShowing) {
                mColorDialog.show()
            }
            return
        }

        mColorDialog = Dialog(mContext, R.style.CustomDialog)
        mColorDialog.setContentView(R.layout.dialog_stamp_color)
        mColorDialog.find<ImageView>(R.id.iv_close).singleClick { mColorDialog.dismiss() }
        // 颜色
        val adapter = StampColorAdapter()
        adapter.setOnItemClickListener { _, _, position ->
            if (NoFastClickUtils.isFastClick()) return@setOnItemClickListener
            if (adapter.updateCheckPosition(position)) {
                stamp_view.setColor(adapter.getItem(position))
            }
        }
        val recyclerView = mColorDialog.find<RecyclerView>(R.id.recycler_color)
        recyclerView.layoutManager =
            LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)
        (recyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recyclerView.adapter = adapter
        // 底部显示
        mColorDialog.bottomShow()
    }

    private fun initTitle() {
        et_content.addTextChangedListener {
            val content = et_content.text.toString()
            when (ctl_stamp_op.currentTab) {
                1 -> stamp_view.textTop = content
                2 -> stamp_view.textBottom = content
                3 -> stamp_view.textCentre = content
            }
        }
        sb_size.seekBarChange { _, i, b ->
            if (!b) return@seekBarChange
            when (ctl_stamp_op.currentTab) {
                1 -> stamp_view.textSizeTop = i
                2 -> stamp_view.textSizeBottom = i
                3 -> stamp_view.textSizeCentre = i
            }
        }
        sb_margin.seekBarChange { _, i, b ->
            if (!b) return@seekBarChange
            when (ctl_stamp_op.currentTab) {
                1 -> stamp_view.textMarginTop = i
                2 -> stamp_view.textMarginBottom = i
                3 -> stamp_view.textMarginCentre = i
            }
        }
        sb_span.seekBarChange { _, i, b ->
            if (!b) return@seekBarChange
            when (ctl_stamp_op.currentTab) {
                1 -> stamp_view.textSpanTop = i
                2 -> stamp_view.textSpanBottom = i
                3 -> stamp_view.textSpanCentre = i
            }
        }
        switch_show.setOnCheckedChangeListener { _, isChecked ->
            when (ctl_stamp_op.currentTab) {
                1 -> stamp_view.isShowTitleTop = isChecked
                2 -> stamp_view.isShowTitleBottom = isChecked
                3 -> stamp_view.isShowTitleCentre = isChecked
            }
        }
    }

    private fun loadTitleTop() {
        et_content.setText(stamp_view.textTop)
        sb_size.progress = stamp_view.textSizeTop
        sb_margin.progress = stamp_view.textMarginTop
        sb_span.progress = stamp_view.textSpanTop
        switch_show.isChecked = stamp_view.isShowTitleTop
    }

    private fun loadTitleCentre() {
        et_content.setText(stamp_view.textCentre)
        sb_size.progress = stamp_view.textSizeCentre
        sb_margin.progress = stamp_view.textMarginCentre
        sb_span.progress = stamp_view.textSpanCentre
        switch_show.isChecked = stamp_view.isShowTitleCentre
    }

    private fun loadTitleBottom() {
        et_content.setText(stamp_view.textBottom)
        sb_size.progress = stamp_view.textSizeBottom
        sb_margin.progress = stamp_view.textMarginBottom
        sb_span.progress = stamp_view.textSpanBottom
        switch_show.isChecked = stamp_view.isShowTitleBottom
    }

    private fun onSave() {
        InputDialog(mContext, "文件名", "请输入签章文件名") { dialog, value ->
            if (value.isEmpty()) {
                toast("请输入签章文件名！")
                return@InputDialog
            }
            dialog.dismiss()
            loadStampImage("${value}.png")
        }.show()
    }

    private fun loadStampImage(fileName: String) {
        showLoadingTipC("正在保存签章文件")
        thread {
            val model = FileModel()
            model.type = Params.fileTypeStamp
            model.fileName = fileName
            model.fileId = "${UserManager.getInstance().userId}/${Params.fileTypeStamp}/${
                System.currentTimeMillis()
            }${fileName.replace(",", "")}"
            model.filePath = ImageUtils.saveBitmapPNG(
                mContext, ImageUtils.getViewBitmap(stamp_view),
                App.getContext().cacheTempPath, fileName
            )
            model.size = FileUtils.getFileSize(model.filePath)
            runOnUiThread {
                if (model.size <= 0) {
                    showNormalTip("保存签章失败")
                } else {
                    OssRequest.getInstance().uploadFile(model, object : OssCallBack {
                        override fun onSuccess() {
                            dismissTip()
                            toast("保存成功~")
                            val resultIntent = Intent()
                            resultIntent.putExtra(Params.flag, 2)
                            resultIntent.putExtra(Params.path, model.filePath)
                            resultIntent.putExtra(Params.type, Params.fileTypeStamp)
                            setResult(RESULT_OK, resultIntent)
                            finish()
                        }

                        override fun onFailure(msg: String) {
                            showNormalTip(msg.ifEmpty { "保存签章失败" })
                        }
                    })
                }
            }
        }
    }
}